# -*- coding: utf-8 -*-

'''
Created on Mar 1, 2009

@author: leonardobessa
'''

import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from random import Random

from Model.entities import *

class AddPersonForm(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
          <html>
           <body>
             <h2>Casdastro de Pessoa</h2>
             <form action="addPerson" method="POST">
                Nome:
                <input name="name"/><br/>
                E-mail:
                <input name="email_address"/><br/>
                Sexo:
                <select name="sex" multiple="false">
                    <option value="M">Masculino</option>
                    <option value="F">Feminino</option>
                    <option value="C">Casado(a)</option>
                </select>
                <br/>
                <input type="submit" value="Cadastrar">
            </form>
           </body>
         </html>""")
    
class AddRoomForm(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
     <html>
       <body>
         <h2>Casdastro de Quarto</h2>
         <form action="addRoom" method="POST">
            Numero:
            <input name="number"/><br/>
            # camas de solteiro:
            <input name="single_beds"/><br/>
            # camas de casal:
            <input name="double_beds"/><br/>
            Sexo:
            <select name="sex" multiple="false">
                <option value="M">Masculino</option>
                <option value="F">Feminino</option>
                <option value="C">Casado(a)</option>
                <option value="Any">Qualquer</option>
            </select><br/>
            <input type="submit" value="Cadastrar">
        </form>
       </body>
     </html>""")

class MakeReservationForm(webapp.RequestHandler):
  def get(self):
    room = Room.get(self.request.get("room.key"))
    people = Person.all()
    people.filter("sex =", room.sex)
    path = os.path.join(os.path.dirname(__file__), 'makeReservationForm.html')
    template_values = {'room': room, 'people': people, 'genre': room.getGenre()}
    self.response.out.write(template.render(path, template_values))

class MakeReservationLogic(webapp.RequestHandler):
  def post(self):
    person = Person.get(self.request.get("personkey"))
    room = Room.get(self.request.get("roomkey"))
    password = self.request.get("password")
    if room.isFull() :
      path = os.path.join(os.path.dirname(__file__), 'reservation.overbook.error.html')
      self.response.out.write(template.render(path,{}))
    return
    if person.sex != room.sex:
       genre = room.getGenre()
       path = os.path.join(os.path.dirname(__file__), 'reservation.sex.error.html')
       self.response.out.write(template.render(path,{"roomkey": room.key(),"genre" : genre}))
       return
    if password != person.password:
      path = os.path.join(os.path.dirname(__file__), 'reservation.password.error.html')
      self.response.out.write(template.render(path,{}))
      return
    person.room = room
    person.put()
    path = os.path.join(os.path.dirname(__file__), 'reservation.ok.html')
    self.response.out.write(template.render(path,{"roomkey": room.key()}))

class AddRoomLogic(webapp.RequestHandler):
  def post(self):
    room = Room(number = int(self.request.get("number")),
                single_beds = int(self.request.get("single_beds")),
                double_beds = int(self.request.get("double_beds")),
                sex = self.request.get("sex")
               )
    room.put()
    self.redirect("/listRooms")


class AddPersonLogic(webapp.RequestHandler):
  def post(self):
   password = self.generatePassword()
   person = Person(name = self.request.get("name"),
                    email_address = self.request.get("email_address"),
                    sex = self.request.get("sex"),
                    is_married = bool(self.request.get("is_married")),
                    password = password
                    )
   person.put()
   message = mail.EmailMessage(sender="nau.organizacao@gmail.com",
                                subject="Reserve seu quarto no NAU 2009 - " + person.name )
   message.to = person.email_address
   
   message.body = """
    Parabéns! Sua inscrição no NAU 2009 foi feita com sucesso!

    Para finalizá-la é necessário reservar o seu quarto.
    
    Você gastará dois minutos e estará colaborando com a organização do hotel.
    
    A sua senha para realizar a reserva de quarto é: 
    %s
    
    Clique no link a seguir, ou copie e cole a URL na barra de endereço do seu navegador:
   
    http://nausampa.appspot.com
    
    Atenciosamente,
    Organização NAU 2009
    """ %   person.password 
   message.send()
   self.redirect("/listPeople")
    

  def generatePassword(self):
      rng = Random()
      righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB'
      lefthand = '789yuiophjknmYUIPHJKLNM'
      allchars = righthand + lefthand
      alternate_hands = True
      passwordLength = 6
      password = ''
      for i in range(passwordLength):
          if not alternate_hands:
              password += rng.choice(allchars)
          else:
            if i % 2:
              password += rng.choice(lefthand)
            else:
              password += rng.choice(righthand)
      return password

class AdminPage(webapp.RequestHandler):

  def get(self):
    people = Person.all()
    people.order("name")
    template_values = {'people': people, 'user': users.get_current_user()}
    path = os.path.join(os.path.dirname(__file__), 'admin.html')
    self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [
                                      ('/admin/', AdminPage),
                                      ('/admin/addRoomForm', AddRoomForm),
                                      ('/admin/addRoom', AddRoomLogic),
                                      ('/admin/addPersonForm', AddPersonForm),
                                      ('/admin/addPerson', AddPersonLogic)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()